<template>
  <div class="volunteer-projects">
    <!-- 项目统计 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stats-card" v-loading="loading.stats">
          <div class="stats-content">
            <div class="stats-icon">
              <el-icon><Calendar /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-value">{{ stats.participatingCount || 0 }}</div>
              <div class="stats-label">正在参与</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card" v-loading="loading.stats">
          <div class="stats-content">
            <div class="stats-icon">
              <el-icon><Timer /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-value">{{ stats.totalHours || 0 }}</div>
              <div class="stats-label">累计时长(小时)</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card" v-loading="loading.stats">
          <div class="stats-content">
            <div class="stats-icon">
              <el-icon><Check /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-value">{{ stats.completedCount || 0 }}</div>
              <div class="stats-label">已完成</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card" v-loading="loading.stats">
          <div class="stats-content">
            <div class="stats-icon">
              <el-icon><Star /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-value">{{ stats.averageRating || 0 }}</div>
              <div class="stats-label">平均评分</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 项目列表 -->
    <el-card class="projects-card" v-loading="loading.list">
      <template #header>
        <div class="card-header">
          <el-radio-group v-model="activeStatus" size="large">
            <el-radio-button label="all">全部项目</el-radio-button>
            <el-radio-button label="participating">正在参与</el-radio-button>
            <el-radio-button label="completed">已完成</el-radio-button>
            <el-radio-button label="upcoming">即将开始</el-radio-button>
          </el-radio-group>

          <div class="header-actions">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索项目名称或主办方"
              class="search-input"
              clearable
              @keyup.enter="handleSearch">
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
        </div>
      </template>

      <el-empty v-if="projects.length === 0" description="暂无项目数据" />

      <el-table v-else :data="projects" style="width: 100%">
        <el-table-column type="expand">
          <template #default="props">
            <div class="project-detail">
              <el-row :gutter="20">
                <el-col :span="16">
                  <div class="detail-item">
                    <h4>项目描述</h4>
                    <p>{{ props.row.description }}</p>
                  </div>
                  <div class="detail-item">
                    <h4>活动地点</h4>
                    <div class="location-info">
                      <p>{{ props.row.location }}</p>
                      <p class="address">{{ props.row.fullAddress }}</p>
                      <el-image
                        :src="props.row.locationImage"
                        :preview-src-list="[props.row.locationImage]"
                        class="location-image"
                      />
                    </div>
                  </div>
                  <div class="detail-item">
                    <h4>活动时间</h4>
                    <p>开始时间：{{ new Date(props.row.date).toLocaleString() }}</p>
                    <p>结束时间：{{ new Date(props.row.endDate).toLocaleString() }}</p>
                    <p>持续时间：{{ Math.floor(props.row.duration / 60) }}小时{{ props.row.duration % 60 }}分钟</p>
                  </div>
                  <div class="detail-item" v-if="props.row.status === 2">
                    <h4>签到记录</h4>
                    <el-timeline>
                      <el-timeline-item
                        v-for="record in props.row.signRecords"
                        :key="record.id"
                        :timestamp="new Date(record.time).toLocaleString()"
                        :type="record.type === 'signIn' ? 'success' : 'info'">
                        {{ record.type === 'signIn' ? '签到' : '签退' }}
                        <template v-if="record.hours">
                          <span class="hours-tag">服务时长：{{ record.hours }}小时</span>
                        </template>
                      </el-timeline-item>
                    </el-timeline>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="detail-item">
                    <h4>我的参与情况</h4>
                    <div class="participation-info">
                      <p>报名时间：{{ new Date(props.row.joinTime).toLocaleString() }}</p>
                      <p>签到次数：{{ props.row.signInCount || 0 }}次</p>
                      <p>累计时长：{{ Math.floor(props.row.myDuration / 60) }}小时{{ props.row.myDuration % 60 }}分钟</p>
                      <p>我的评价：{{ props.row.myRating ? `${props.row.myRating}分` : '暂未评价' }}</p>
                    </div>
                  </div>
                  <div class="detail-item">
                    <h4>操作</h4>
                    <div class="action-buttons">
                      <el-button 
                        v-if="props.row.status === 1 && props.row.auditStatus === 1"
                        type="primary" 
                        @click="handleJoin(props.row)">
                        报名
                      </el-button>
                      <el-button 
                        v-if="props.row.status === 2"
                        type="success" 
                        @click="handleSign(props.row)">
                        签到
                      </el-button>
                      <el-button 
                        v-if="props.row.status === 2"
                        type="warning" 
                        @click="handleRecordHours(props.row)">
                        登记时长
                      </el-button>
                      <el-button 
                        v-if="props.row.status === 1 || props.row.status === 2"
                        type="danger" 
                        @click="handleQuit(props.row)">
                        退出项目
                      </el-button>
                      <el-button 
                        v-if="props.row.status === 3 && !props.row.myRating"
                        type="primary" 
                        @click="handleRate(props.row)">
                        评价项目
                      </el-button>
                      <el-button 
                        type="info" 
                        @click="viewDetail(props.row)">
                        查看完整详情
                      </el-button>
                    </div>
                  </div>
                </el-col>
              </el-row>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="title" label="项目名称" min-width="200">
          <template #default="scope">
            <div class="project-name">
              <el-image
                :src="scope.row.image || 'https://placeholder.com/100'"
                :preview-src-list="scope.row.image ? [scope.row.image] : []"
                class="project-image"
              />
              <span>{{ scope.row.title }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="organizationName" label="主办方" width="150" />

        <el-table-column label="时间" width="180">
          <template #default="scope">
            {{ new Date(scope.row.date).toLocaleString() }}
          </template>
        </el-table-column>

        <el-table-column label="我的时长" width="100">
          <template #default="scope">
            {{ Math.floor(scope.row.myDuration / 60) }}小时
          </template>
        </el-table-column>

        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="320" fixed="right">
          <template #default="scope">
            <div class="action-buttons">
              <el-button 
                v-if="scope.row.status === 1 && scope.row.auditStatus === 1"
                type="primary" 
                link
                @click="handleJoin(scope.row)">
                报名
              </el-button>
              <el-button 
                v-if="scope.row.status === 2"
                type="success" 
                link
                @click="handleSign(scope.row)">
                签到
              </el-button>
              <el-button 
                v-if="scope.row.status === 2"
                type="warning" 
                link
                @click="handleRecordHours(scope.row)">
                登记时长
              </el-button>
              <el-button 
                v-if="scope.row.status === 1 || scope.row.status === 2"
                type="danger" 
                link
                @click="handleQuit(scope.row)">
                退出
              </el-button>
              <el-button 
                v-if="scope.row.status === 3 && !scope.row.myRating"
                type="primary" 
                link
                @click="handleRate(scope.row)">
                评价
              </el-button>
              <el-button 
                type="info" 
                link
                @click="viewDetail(scope.row)">
                详情
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination" v-if="total > 0">
        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          background
          layout="prev, pager, next"
        />
      </div>
    </el-card>

    <!-- 评价对话框 -->
    <el-dialog
      v-model="rateDialogVisible"
      title="项目评价"
      width="500px"
    >
      <el-form :model="rateForm" label-width="80px">
        <el-form-item label="评分">
          <el-rate
            v-model="rateForm.rating"
            :texts="['很差', '较差', '一般', '较好', '很好']"
            show-text
          />
        </el-form-item>
        <el-form-item label="评价内容">
          <el-input
            v-model="rateForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入您的评价内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="rateDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRate">提交评价</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { 
  Calendar, Timer, Star, Check, Search,
  OfficeBuilding, Location
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { 
  getVolunteerProjects, 
  getProjectDetail,
  signInProject,
  quitProject,
  rateProject,
  recordServiceHours
} from '@/api/volunteer-dashboard'

const router = useRouter()
const activeStatus = ref('all')
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 加载状态
const loading = ref({
  stats: false,
  list: false
})

// 项目统计
const stats = ref({
  participatingCount: 0,
  totalHours: 0,
  completedCount: 0,
  averageRating: 0
})

// 项目列表
const projectList = ref([])

// 评价相关
const rateDialogVisible = ref(false)
const rateForm = ref({
  projectId: null,
  rating: 5,
  content: ''
})

// 处理过滤后的项目数据
const projects = computed(() => {
  let result = [...projectList.value]
  
  // 按状态筛选
  if (activeStatus.value !== 'all') {
    result = result.filter(item => {
      switch (activeStatus.value) {
        case 'participating':
          return item.status === 1 || item.status === 2
        case 'completed':
          return item.status === 3
        case 'upcoming':
          return item.status === 0
        default:
          return true
      }
    })
  }
  
  // 按关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(
      item => item.title.toLowerCase().includes(keyword) || 
             item.organizationName.toLowerCase().includes(keyword)
    )
  }
  
  return result
})

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    0: 'info',    // 未开始
    1: 'warning', // 报名中
    2: 'success', // 进行中
    3: 'danger'   // 已结束
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    0: '未开始',
    1: '报名中',
    2: '进行中',
    3: '已结束'
  }
  return texts[status] || '未知'
}

// 获取项目统计和列表
const fetchProjects = async () => {
  loading.value.stats = true
  loading.value.list = true
  
  try {
    const res = await getVolunteerProjects({
      page: currentPage.value,
      pageSize: pageSize.value,
      status: activeStatus.value === 'all' ? '' : activeStatus.value,
      keyword: searchKeyword.value
    })
    
    if (res.code === 200) {
      projectList.value = res.data.list.map(item => ({
        ...item,
        signRecords: item.signRecords || [],
        myDuration: item.myDuration || 0,
        signInCount: item.signInCount || 0,
        myRating: item.myRating || null,
        lastSignIn: item.lastSignIn || null,
        lastSignOut: item.lastSignOut || null
      }))
      
      total.value = res.data.total
      currentPage.value = res.data.page
      pageSize.value = res.data.pageSize
      
      // 更新统计数据
      stats.value.participatingCount = projectList.value.filter(p => p.status === 1 || p.status === 2).length
      stats.value.completedCount = projectList.value.filter(p => p.status === 3).length
      stats.value.totalHours = projectList.value.reduce((sum, project) => sum + (project.myDuration || 0), 0) / 60
      stats.value.averageRating = projectList.value.reduce((sum, project) => sum + (project.myRating || 0), 0) / projectList.value.length
    } else {
      ElMessage.error(res.message || '获取项目列表失败')
    }
  } catch (error) {
    ElMessage.error('获取项目列表失败：' + (error.message || '未知错误'))
  } finally {
    loading.value.stats = false
    loading.value.list = false
  }
}

// 查看项目详情
const viewDetail = (project) => {
  router.push(`/volunteer/projects/${project.id}`)
}

// 项目签到
const handleSign = async (project) => {
  try {
    const { value: type } = await ElMessageBox.confirm(
      '请选择签到类型',
      '签到',
      {
        distinguishCancelAndClose: true,
        confirmButtonText: '签到',
        cancelButtonText: '签退',
        type: 'info'
      }
    )
    
    const signType = type === 'confirm' ? 'signIn' : 'signOut'
    const res = await signInProject({
      projectId: project.id,
      type: signType
    })
    
    if (res.code === 200) {
      ElMessage.success(`已成功${signType === 'signIn' ? '签到' : '签退'}`)
      fetchProjects()
    } else {
      ElMessage.error(res.message || '操作失败')
    }
  } catch (error) {
    if (error !== 'cancel' && error !== 'close') {
      ElMessage.error('操作失败：' + (error.message || '未知错误'))
    }
  }
}

// 退出项目
const handleQuit = async (project) => {
  try {
    await ElMessageBox.confirm(
      `确定要退出项目"${project.title}"吗？`,
      '退出确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const res = await quitProject(project.id)
    if (res.code === 200) {
      ElMessage.success(`已成功退出项目"${project.title}"`)
      fetchProjects()
    } else {
      ElMessage.error(res.message || '退出失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('退出失败：' + (error.message || '未知错误'))
    }
  }
}

// 打开评价对话框
const handleRate = (project) => {
  rateForm.value = {
    projectId: project.id,
    rating: 5,
    content: ''
  }
  rateDialogVisible.value = true
}

// 提交评价
const submitRate = async () => {
  try {
    const res = await rateProject(rateForm.value)
    if (res.code === 200) {
      ElMessage.success('评价提交成功')
      rateDialogVisible.value = false
      fetchProjects()
    } else {
      ElMessage.error(res.message || '评价提交失败')
    }
  } catch (error) {
    ElMessage.error('评价提交失败：' + (error.message || '未知错误'))
  }
}

// 登记服务时长
const handleRecordHours = async (project) => {
  try {
    const { value: form } = await ElMessageBox.prompt(
      '请输入本次服务时长（小时）',
      '登记服务时长',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^[0-9]+(\.[0-9]{1,2})?$/,
        inputErrorMessage: '请输入正确的时长（如：2.5）',
        inputType: 'number',
        inputValue: '1'
      }
    )
    
    const res = await recordServiceHours({
      projectId: project.id,
      hours: parseFloat(form),
      date: new Date().toISOString().split('T')[0] // 默认使用当天日期
    })
    
    if (res.code === 200) {
      ElMessage.success('服务时长登记成功')
      fetchProjects()
    } else {
      ElMessage.error(res.message || '登记失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('登记失败：' + (error.message || '未知错误'))
    }
  }
}

// 监听筛选条件变化
watch([activeStatus, currentPage], () => {
  fetchProjects()
})

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchProjects()
}

// 页面加载时获取数据
onMounted(() => {
  fetchProjects()
})
</script>

<style scoped lang="scss">
.volunteer-projects {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;

  .stats-row {
    margin-bottom: 24px;
  }

  .stats-card {
    height: 100%;
    transition: all 0.3s;

    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }

    .stats-content {
      display: flex;
      align-items: center;
      padding: 24px;

      .stats-icon {
        width: 56px;
        height: 56px;
        border-radius: 12px;
        background: #ecf5ff;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 20px;
        flex-shrink: 0;

        .el-icon {
          font-size: 28px;
          color: #409EFF;
        }
      }

      .stats-info {
        flex: 1;
        min-width: 0;

        .stats-value {
          font-size: 28px;
          font-weight: bold;
          color: #303133;
          line-height: 1.2;
          margin-bottom: 8px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        .stats-label {
          font-size: 14px;
          color: #909399;
        }
      }
    }
  }

  .projects-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16px 20px;
      border-bottom: 1px solid #ebeef5;

      .el-radio-group {
        margin-right: 20px;
      }

      .header-actions {
        display: flex;
        align-items: center;
        gap: 16px;

        .search-input {
          width: 300px;
        }
      }
    }

    .project-name {
      display: flex;
      align-items: center;
      gap: 12px;

      .project-image {
        width: 48px;
        height: 48px;
        border-radius: 6px;
        object-fit: cover;
      }

      span {
        font-weight: 500;
        color: #303133;
      }
    }

    .project-detail {
      padding: 24px;

      .detail-item {
        margin-bottom: 24px;

        h4 {
          margin: 0 0 12px;
          font-size: 15px;
          font-weight: 500;
          color: #303133;
          display: flex;
          align-items: center;
          gap: 8px;

          &::before {
            content: '';
            display: inline-block;
            width: 4px;
            height: 16px;
            background: #409EFF;
            border-radius: 2px;
          }
        }

        p {
          margin: 0 0 8px;
          color: #606266;
          line-height: 1.6;
          font-size: 14px;

          &.address {
            color: #909399;
            font-size: 13px;
          }
        }

        .location-info {
          .location-image {
            width: 100%;
            max-width: 400px;
            border-radius: 8px;
            margin-top: 12px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
          }
        }

        .participation-info {
          p {
            margin-bottom: 12px;
            display: flex;
            align-items: center;
            gap: 8px;

            &::before {
              content: '';
              display: inline-block;
              width: 6px;
              height: 6px;
              background: #409EFF;
              border-radius: 50%;
            }
          }
        }

        .action-buttons {
          display: flex;
          flex-direction: column;
          gap: 12px;

          .el-button {
            width: 100%;
            margin-left: 0;
          }
        }
      }
    }

    .pagination {
      margin-top: 24px;
      padding: 16px 20px;
      border-top: 1px solid #ebeef5;
      text-align: right;
    }
  }

  :deep(.el-table) {
    .el-table__header {
      th {
        background-color: #f5f7fa;
        color: #606266;
        font-weight: 500;
        padding: 12px 0;
      }
    }

    .el-table__row {
      td {
        padding: 16px 0;
      }
    }
  }

  .hours-tag {
    margin-left: 8px;
    padding: 2px 6px;
    background: #f0f9eb;
    color: #67c23a;
    border-radius: 4px;
    font-size: 12px;
  }
}
</style> 